package tw.twandroidproj.app.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.orm.SugarRecord;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.NetworkManager;
import tw.twandroidproj.app.network.OnResponseListener;
import tw.twandroidproj.app.ui.activity.LoginActivity;
import tw.twandroidproj.app.ui.personal.SelectPicPopupWindow;

/**
 * Created by freeze on 2015/4/11.
 * 个人信息fragment
 */
public class PersonalFragment extends Fragment {
    private TextView textView1, textView2, textView3, textView4, textView5,textView6,textView7;
    private AuthManager LoginAuth;
    private NetworkManager Networkstuff;
    private Button save;
    SelectPicPopupWindow menuWindow;
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:takePhoto();
                    break;
                case R.id.btn_pick_photo:getPhoto();
                    break;
                default:
                    break;
            }


        }

    };
    private void getPhoto() {
        Intent intent=new Intent();
        intent.setType("image/*");
        //intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 2);



    }
    private Uri getUri(){
        String path;
        path= Environment.getExternalStorageDirectory().getPath();
        path=path+"/"+"tem.png";
        File file=new File(path);
        Uri uri= Uri.fromFile(file);//资源定位
        return uri;
    }
    public void  takePhoto(){

        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0);
        startActivityForResult(intent, 1);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode== Activity.RESULT_OK) {   Log.e("TAG", "onActivityResult: sa");
            switch (requestCode){
                case 1:cropPhoto(getUri());break;

                case 2:cropPhoto(data.getData());break;
                case 3:
                    Bundle bundle=data.getExtras();
                    Bitmap bitmap=bundle.getParcelable("data");
                    if(bitmap!=null){
                        Drawable drawable=new BitmapDrawable(bitmap);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        textView7.setCompoundDrawables(null, null, drawable, null);
                    }
                    break;
            }



        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public   void cropPhoto(Uri uri){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");//?
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent,3);
    }

    @Override


    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        LoginAuth=AuthManager.getInstance(this.getActivity());
        Networkstuff=NetworkManager.getInstance(this.getActivity());

        if (LoginAuth.isLogined()==false){
            Intent intent=new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        Toast.makeText(getActivity(),"您还未登录",Toast.LENGTH_SHORT).show();}

        final View layout = inflater.inflate(R.layout.fragment_personal, container, false);

        if (LoginAuth.isLogined()){
            TextView login_nickname=(TextView) layout.findViewById(R.id.login_name);
            login_nickname.setText(LoginAuth.getLoginUser().getNickname());

            TextView login_age=(TextView) layout.findViewById(R.id.login_age);
            login_age.setText(LoginAuth.getLoginUser().getBirthday());

            TextView login_email=(TextView) layout.findViewById(R.id.login_email);
            login_email.setText(LoginAuth.getLoginUser().getEmail());

            TextView login_sex=(TextView) layout.findViewById(R.id.login_xingbie);
            if (LoginAuth.getLoginUser().getSex()==1) login_sex.setText("男");
            else login_sex.setText("女");

            TextView login_location=(TextView) layout.findViewById(R.id.login_location);
            login_location.setText(LoginAuth.getLoginUser().getLocation());

            TextView login_sign=(TextView) layout.findViewById(R.id.login_qianming);
            login_sign.setText(LoginAuth.getLoginUser().getSign());

        }

        textView7=(TextView)layout.findViewById(R.id.touxiang);
        textView7.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

                menuWindow = new SelectPicPopupWindow(getActivity(),itemsOnClick);
                menuWindow.showAtLocation(layout.findViewById(R.id.touxiang), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);


            }
        });

       textView1=(TextView)layout.findViewById(R.id.nichen);
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                builder.setIcon(R.mipmap.ic_launcher);
//                builder.setTitle("请输入您的昵称");
                //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_name, null);
                //    设置我们自己定义的布局文件作为弹出框的Content
                builder.setView(view);

                final EditText username = (EditText)view.findViewById(R.id.username);
                TextView hint = (TextView) layout.findViewById(R.id.login_name);
                String m=hint.getText().toString().trim();
                username.setText(m);
                username.setSelection(m.length());


                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String a = username.getText().toString().trim();

                        TextView mTextView = (TextView) layout.findViewById(R.id.login_name);
                        mTextView.setText(a);


                    }


                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
            }
        });

        textView2=(TextView)layout.findViewById(R.id.gender);
        textView2.setOnClickListener(new View.OnClickListener() {
          int a;

            @Override
            public void onClick(View view) {



            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("请选择性别");
                final String[] sex = {"男", "女", "未知性别"};
                //    设置一个单项选择下拉框
                /**
                 * 第一个参数指定我们要显示的一组下拉单选框的数据集合
                 * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认‘女‘ 会被勾选上
                 * 第三个参数给每一个单选项绑定一个监听器

*/
                builder.setSingleChoiceItems(sex, 1, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        a = which;
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        TextView mTextView= (TextView) layout.findViewById(R.id.login_xingbie);
                        mTextView.setText(sex[a]);


                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                builder.show();
            }
        });
        textView3=(TextView)layout.findViewById(R.id.age);
        textView3.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                builder.setIcon(R.mipmap.ic_launcher);
//                builder.setTitle("请输入您的年龄");
                //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_age, null);
                //    设置我们自己定义的布局文件作为弹出框的Content
                builder.setView(view);

                final EditText userage = (EditText)view.findViewById(R.id.userage);
                TextView hint2 = (TextView) layout.findViewById(R.id.login_age);
                String m2=hint2.getText().toString().trim();
                userage.setText(m2);
                userage.setSelection(m2.length());

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        String a = userage.getText().toString().trim();

                        //    将输入的用户名和密码打印出来
                        TextView mTextView= (TextView) layout.findViewById(R.id.login_age);
                        mTextView.setText(a);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                builder.show();
            }
        });
        textView4=(TextView)layout.findViewById(R.id.email);
        textView4.setOnClickListener(new View.OnClickListener() {


            @Override

            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                builder.setIcon(R.mipmap.ic_launcher);
//                builder.setTitle("请输入您的电子邮箱地址");
                //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_email, null);
                //    设置我们自己定义的布局文件作为弹出框的Content
                builder.setView(view);

                final EditText useremail = (EditText)view.findViewById(R.id.useremail);
                TextView hint3 = (TextView) layout.findViewById(R.id.login_email);
                String m3=hint3.getText().toString().trim();
                useremail.setText(m3);
                useremail.setSelection(m3.length());

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        String a = useremail.getText().toString().trim();

                        //    将输入的用户名和密码打印出来
                        TextView mTextView= (TextView) layout.findViewById(R.id.login_email);
                        mTextView.setText(a);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                builder.show();
            }
        });
        textView5=(TextView)layout.findViewById(R.id.loc);
        textView5.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("选择一个城市");
                //    指定下拉列表的显示数据
                final String[] cities = {"浙江","江苏","广州", "上海", "北京", "香港", "澳门"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        TextView mTextView= (TextView) layout.findViewById(R.id.login_location);
                        mTextView.setText(cities[which]);
                    }
                });
                builder.show();
            }
        });






        textView6=(TextView)layout.findViewById(R.id.qianming);
        textView6.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                builder.setIcon(R.mipmap.ic_launcher);
//                builder.setTitle("请输入您的个性签名");
                //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_qianming, null);
                //    设置我们自己定义的布局文件作为弹出框的Content
                builder.setView(view);

                final EditText userqianming = (EditText)view.findViewById(R.id.userqianming);
                TextView hint4 = (TextView) layout.findViewById(R.id.login_qianming);
                String m4=hint4.getText().toString().trim();
                userqianming.setText(m4);
                userqianming.setSelection(m4.length());

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        String a = userqianming.getText().toString().trim();

                        //    将输入的用户名和密码打印出来
                        TextView mTextView= (TextView) layout.findViewById(R.id.login_qianming);
                        mTextView.setText(a);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                builder.show();
            }
        });

        save=(Button)layout.findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener(){


            @Override
            public void onClick(View view) {
                TextView t1 = (TextView) layout.findViewById(R.id.login_name);
                TextView t2 = (TextView) layout.findViewById(R.id.login_email);
                TextView t3 = (TextView) layout.findViewById(R.id.login_age);
                TextView t4 = (TextView) layout.findViewById(R.id.login_location);
                TextView t5 = (TextView) layout.findViewById(R.id.login_qianming);
                TextView t6 = (TextView) layout.findViewById(R.id.login_xingbie);
                int sex;
                String name=t1.getText().toString().trim();
                String email=t2.getText().toString().trim();
                String  age=t3.getText().toString().trim();
                String location=t4.getText().toString().trim();
                String qianming=t5.getText().toString().trim();
                if(t6.getText().toString().trim()=="男")sex=1;else sex=0;

                LoginAuth.getLoginUser().setNickname(name);
                LoginAuth.getLoginUser().setEmail(email);
                LoginAuth.getLoginUser().setBirthday(age);
                LoginAuth.getLoginUser().setSex(sex);
                LoginAuth.getLoginUser().setLocation(location);
                LoginAuth.getLoginUser().setSign(qianming);

                SugarRecord.save(LoginAuth.getLoginUser());
                Map<String, String> map = new HashMap<String, String>();
                map.put("nickname", name);
                map.put("age",age);
                map.put("location",location);
                map.put("sign",qianming);
                map.put("sex", String.valueOf(sex));
                Networkstuff.userUpdate(LoginAuth.getToken(),LoginAuth.getLoginUser().getUid(), map, new OnResponseListener<String>() {


                    @Override
                    public void onSuccess(String result) {
                        Toast.makeText(getActivity(), "修改成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailed(ErrorModel errorModel) {
                        Toast.makeText(getActivity(), "修改失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

    return  layout;


    }



}
